<template>
	<view class="content">
    <view v-show="!changeStart" class="selectDevice" @click="commitDevice">
      确定分配
    </view>
    <view class="myFacility">
      <view class="realBox">
        <view class="setIcon" v-if="changeStart" @click="deviceAllotFun">设备分配</view>
        <view class="setIcon" v-if="!changeStart" @click="cancelAllot">取消分配</view>
        <view class="setIcon" @click="watchGroup">查看组合</view>
        <view class="setIcon" @click="addGroup">
          <span>新增设备</span>
        </view>
      </view>
    </view>
    <div class="MainBody">
      <u-search
        :showAction="true"
        actionText="搜索"
        :animation="true"
        @custom="seatchDevice"
        v-model="SearchVal" />
        <view :class="changeStart ? 'realBox_one' : 'changeBox'" v-for="(item,index) in deviceList" :key="index">
          <view class="deviceBox">
            <span style="font-weight: 600;">设备名称：</span>{{ item.name }}
          </view>
          <view class="radioPos" v-show="!changeStart">
            <u-checkbox-group @change="checkboxChange(index)">
              <u-checkbox size="40" v-model="item.isCheckedinEqui" shape="circle"></u-checkbox>
            </u-checkbox-group>
          </view>
          <view class="deviceBox">
            <span style="font-weight: 600;">厂商：</span>{{ item.manufacturerName }}
          </view>
          <view class="deviceBox">
            <span style="font-weight: 600;">创建时间：</span>{{ item.createTime | setTime }}
          </view>
          <view class="deviceBox">
            <span style="font-weight: 600;">设备类型：</span>{{ item.deviceType === 0 ? '网关' : item.deviceType === 1 ? '温湿度' : item.deviceType === 2 ? '开关' : item.deviceType === 3 ? '土壤温湿度' : '秤'}}
          </view>
          <view class="deviceBox" v-if="item.deviceType === 2">
            <span style="font-weight: 600;">设备状态：</span>
            <u-switch size="50" v-model="item.status" @change="changeStatus(item,index)"></u-switch>
          </view>
          
          <view class="lastForDevice">
            <view class="customButton" @click="ToDetails(item.id,item.manufacturerName)">查看</view>
            <view class="customButton" @click="setDeviceDetail(item.id,item.manufacturerName,item.manufacturerId)">修改</view>
          </view>
        </view>
        
        <u-loadmore 
          :status="statusLoamore" 
          @loadmore="clickLoadmore" 
          fontSize="36rpx" 
          line
          :loading-text="loadingText" 
          :loadmore-text="loadmoreText" 
          :nomore-text="nomoreTextTah"/>
    </div>
    <u-popup
      mode="center"
      :show="showAddGroup"
      @close="closeGroup">
        <view class="addBox">
          <view class="addTitle">
            新增设备
          </view>
          <u--form
            labelWidth="120px"
            labelPosition="left"
            :model="modelSwich"
            :rules="rulesSwich"
            ref="uForm"
          >
            <u-form-item
              label="设备名称"
              prop="switchModel.name"
              borderBottom
              ref="item"
            >
              <u--input
                v-model="modelSwich.switchModel.name"
                placeholder="请输入设备名称"
                border="none"
              ></u--input>
            </u-form-item>
            <u-form-item
              label="设备密钥"
              prop="switchModel.deviceKey"
              borderBottom
              ref="item"
            >
              <u--input
                v-model="modelSwich.switchModel.deviceKey"
                placeholder="请输入设备密钥"
                border="none"
              ></u--input>
            </u-form-item>
            <u-form-item
              label="设备编号"
              prop="switchModel.deviceNum"
              borderBottom
              ref="item"
            >
              <u--input
                v-model="modelSwich.switchModel.deviceNum"
                placeholder="请输入设备编号"
                border="none"
              ></u--input>
            </u-form-item>
            <u-form-item
              label="设备类型"
              prop="switchModel.gateway"
              @click="showSexFun"
              borderBottom
              ref="item"
            >
              <u--input
                v-model="modelSwich.switchModel.gateway"
                placeholder="请选择设备类型"
                disabled
                disabledColor="#ffffff"
                border="none"
              ></u--input>
              <u-icon
                slot="right"
                name="arrow-right"
              ></u-icon>
            </u-form-item>
            <u-form-item
              label="厂商"
              prop="switchModel.factory"
              @click="showfactoryFun"
              borderBottom
              ref="item"
            >
              <u--input
                v-model="modelSwich.switchModel.factory"
                placeholder="请选择设备厂商"
                disabled
                disabledColor="#ffffff"
                border="none"
              ></u--input>
              <u-icon
                slot="right"
                name="arrow-right"
              ></u-icon>
            </u-form-item>
            
            <u-form-item
              label="网关"
              v-if="isShowGetway"
              prop="switchModel.factory"
              @click="showGatewayFun"
              borderBottom
              ref="item"
            >
              <u--input
                v-model="modelSwich.switchModel.getwatName"
                placeholder="请选择设备网关"
                disabled
                disabledColor="#ffffff"
                border="none"
              ></u--input>
              <u-icon
                slot="right"
                name="arrow-right"
              ></u-icon>
            </u-form-item>
            <u-form-item
              label="开关总路数"
              v-if="modelSwich.switchModel.myGetwayId === 2"
              prop="switchModel.switchCount"
              borderBottom
              ref="item"
            >
              <u--input
                v-model="modelSwich.switchModel.switchCount"
                placeholder="请输入开关总路数"
                @blur="getSwitchStartNum"
                border="none"
              ></u--input>
            </u-form-item>
            <u-form-item
              label="开关初始路数"
              v-if="modelSwich.switchModel.switchCount != '' && modelSwich.switchModel.myGetwayId === 2"
              @click="showStartFunNumSwitch"
              borderBottom
              ref="item"
            >
              <u--input
                v-model="modelSwich.switchModel.startNum"
                placeholder="请选择开关初始路数"
                disabled
                disabledColor="#ffffff"
                border="none"
              ></u--input>
              <u-icon
                slot="right"
                name="arrow-right"
              ></u-icon>
            </u-form-item>
            <u-form-item
              label="备注"
              borderBottom
              ref="item"
            >
              <u--input
                v-model="modelSwich.switchModel.remark"
                placeholder="请输入备注"
                border="none"
              ></u--input>
            </u-form-item>
            <!-- <u-form-item
              v-if="modelSwich.switchModel.myGetwayId === 2"
              label="状态"
              borderBottom
              ref="item"
            >
              <u--input
                v-model="modelSwich.switchModel.status"
                placeholder="请输入状态"
                border="none"
              ></u--input>
            </u-form-item> -->
            <view class="lastForSwitch">
              <view @click="submitSwitch">提交</view>
              <view @click="showAddGroup = false">关闭</view>
            </view>
          </u--form>
        </view>
		</u-popup>
    <u-action-sheet
      :show="showSex"
      :actions="deviceTypeArr"
      title="请选择设备类型"
      @close="showSex = false"
      @select="deviceTypeSelect"
    >
    </u-action-sheet>
    <u-action-sheet
      :show="showfactory"
      :actions="factoryArr"
      title="请选择厂商"
      @close="showfactory = false"
      @select="factorySelect"
    >
    </u-action-sheet>
    <u-action-sheet
      :show="sheetShowGateway"
      :actions="getwatArr"
      title="请选择网关"
      @close="sheetShowGateway = false"
      @select="getwaySelect"
    >
    </u-action-sheet>
    <u-action-sheet
      :show="showSwitchStartNum"
      :actions="startArrNumForSwitch"
      title="请选择开关初始路数"
      @close="showSwitchStartNum = false"
      @select="startSelect"
    >
    </u-action-sheet>
	</view>
</template>

<script>
  import request from './../../request/api';
  import { timestampToDatetime } from '@/untils/index';
	export default {
		data() {
			return {
        tagFactory: '',
        startArrNumForSwitch: [],
        showSwitchStartNum: false,
        sheetShowGateway: false,
        getwatArr: [],
        isShowGetway: false,
        initStatus: false,
        changeStart: true,
        statusLoamore:'loadmore',
        loadingText: '加载中...',
        loadmoreText: '加载更多',
        nomoreTextTah: '已加载完',
        SearchVal:'',
        deviceList:[],
        showfactory: false,
        factoryArr:[],
        showAddGroup: false,
        showSex: false,
        deviceTypeArr: [
          {
            id: 0,
            name: '网关'
          },
          {
            id: 1,
            name: '温湿度'
          },
          {
            id: 2,
            name: '开关'
          },
          {
            id: 3,
            name: '土壤温湿度'
          },
          {
            id: 4,
            name: '秤'
          },
          {
            id: 5,
            name: '氨气'
          }
        ],
        modelSwich: {
          switchModel :{
            startNum: '',
            name:'',
            deviceKey: '',
            switchCount: '',
            deviceNum: '',
            gateway: '',
            myGetwayId: '',
            factoryID: '',
            factory: '',
            remark:'',
            status: 0,
            getwatID: '',
            getwatName: ''
          }
        },
        rulesSwich: {
          'switchModel.name': {
            type: 'string',
            required: true,
            message: '请填写设备名称',
            trigger: ['blur', 'change']
          },
          'switchModel.deviceKey': {
            type: 'string',
            required: true,
            message: '请填写设备密钥',
            trigger: ['blur', 'change']
          },
          'switchModel.deviceNum': {
            type: 'string',
            required: true,
            message: '请填写设备编号',
            trigger: ['blur', 'change']
          },
          'switchModel.gateway': {
            type: 'string',
            required: true,
            message: '请选择网关',
            trigger: ['blur', 'change']
          },
          'switchModel.factory': {
            type: 'string',
            required: true,
            message: '请选择厂商',
            trigger: ['blur', 'change']
          }
        },
        pagetion:{
          page:1,
          limit: 5,
          total: 1
        },
			}
		},
    components: {
		},
    filters: {
      setTime(val){
        return timestampToDatetime(val)
      }
		},
		onLoad() {
      
		},
    onShow(){
      this.pagetion.page = 1
      this.getManufacturer()
      this.getDeviceList()
      this.changeStart = true
    },
		methods: {
      deviceAllotFun(){
        if (this.deviceList.length < 1) {
          uni.$u.toast('请先新增设备')
        } else {
          this.changeStart = false
        }
      },
      showStartFunNumSwitch(){
        this.showSwitchStartNum = true
      },
      getSwitchStartNum(val){
        this.modelSwich.switchModel.startNum = ''
        this.startArrNumForSwitch = []
        for (let index = 0; index < val; index++) {
          this.startArrNumForSwitch.push({
            name: index+1
          })
        }
        
      },
      startSelect(val){
        this.modelSwich.switchModel.startNum = val.name
        this.showSwitchStartNum = false
      },
      changeStatus(val,valB){
        // console.log(val,valB);
        
        let options = {
          url: '/device/update',
          method: 'post',
          data: {
            switchCount: val.switchCount,
            deviceId: val.id,
            deviceKey: val.deviceKey,
            deviceNum: val.num,
            deviceType: val.deviceType,
            manufacturerId: val.fId,
            gatewayId: val.gatewayId,
            name: val.name,
            remark: val.remark,
            status: val.status = val.status === true ? 1 : 0,
            switchNum: val.switchNum
          }
        }
        request(options).then(res => {
          if (res.code === '200') {
            uni.$u.toast('操作成功')
            val.status = val.status === 0 ? false : true
            this.deviceList[valB].status = val.status
          } else {
            uni.$u.toast(result.message)
          }
        })
        
      },
      watchGroup(){
        uni.navigateTo({
          url: `./gruopList`
        })
      },
      cancelAllot(){
        for (const el of this.deviceList) {
          el.isCheckedinEqui = false
        }
        this.changeStart = true
      },
      checkboxChange(val){
        this.deviceList[val].isCheckedinEqui = !this.deviceList[val].isCheckedinEqui
      },
      commitDevice(){
        const nullArr = []
        for (const el of this.deviceList) {
          if (el.isCheckedinEqui === true) {
            el.isChecked = false
            nullArr.push(el)
          }
        }
        const arr = JSON.stringify(nullArr)
        uni.navigateTo({
          url:`./deviceAllot?nullArr=${arr}`
        })
      },
      clickLoadmore(){
        if ((this.pagetion.page * this.pagetion.limit) >= this.pagetion.total ) {
          this.statusLoamore = 'nomore'
          return 
        } else {
          setTimeout(() => {
            this.statusLoamore = 'loading';
            const pageNum = ++this.pagetion.page
            this.getDeviceList(pageNum)
          }, 500);
        }
      },
      onReachBottom(){
        if ((this.pagetion.page * this.pagetion.limit) >= this.pagetion.total ) {
          this.statusLoamore = 'nomore'
          return 
        } else {
          setTimeout(() => {
            this.statusLoamore = 'loading';
            const pageNum = ++this.pagetion.page
            this.getDeviceList(pageNum)
          }, 500);
        }
      },
      setDeviceDetail(id,manName,ManID){
        uni.navigateTo({
          url:`./update?id=${id}&name=${manName}&ManId=${ManID}`
        })
      },
      ToDetails(id,name){
        uni.navigateTo({
          url:`./details?id=${id}&name=${name}`
        })
      },
      seatchDevice(kw){
        this.pagetion.page = 1
        this.tahList = [] 
        this.deviceList = []
        if (kw !== '') {
          let options = {
            url: '/device/list',
            method: 'GET',
            data: {
              limit: 5,
              page: this.pagetion.page,
              kw: kw
            }
          }
          request(options).then((result)=> {
            if (result.code === '200') {
              const nullArr = result.data.records
              for (const el of nullArr) {
                el.isCheckedinEqui = false
                el.status = el.status === 0 ? false : true
              }
              this.deviceList.push(...nullArr)
            }
          })
        } else {
          this.getDeviceList()
        }
      },
      getDeviceList(val = 1){
        let options = {
          url: '/device/list',
          method: 'GET',
          data: {
            limit: 5,
            page: val,
            kw: ''
          }
        }
        request(options).then((result)=> {
          if (result.code === '200') {
            const nullArr = result.data.records
            this.pagetion.total = result.data.total
            if (this.deviceList.length >= result.data.total) {
              return false
            } else if(val === 1){
              this.deviceList = nullArr
            }else{
              for (const el of nullArr) {
                el.isCheckedinEqui = false
                el.status = el.status === 0 ? false : true
              }
              this.deviceList.push(...nullArr)
            }
          }
        })
      },
      showfactoryFun(){
        if (this.showSex === true) {
          this.showSex = false
        } 
        this.showfactory = true
      },
      showSexFun(){
        if (this.showfactory === true) {
          this.showfactory = false
        }
        this.showSex = true
      },
      getManufacturer(){
        const switchObj = {
          url: '/manufacturer/all',
          method: 'GET',
        }
        request(switchObj).then(result => {
          if (result.code === '200') {
            this.factoryArr = result.data
          } else {
            uni.$u.toast(result.message)
          }
        })
      },
      addGroup(){
        this.showAddGroup = true
      },
      closeGroup(){
        this.showAddGroup = false
      },
      submitSwitch(){
        this.$refs.uForm.validate().then(resLgo => {
          let obj = {
            url: '/device/add',
            method: 'post',
            data: {
              deviceType: this.modelSwich.switchModel.myGetwayId,
              deviceKey: this.modelSwich.switchModel.deviceKey,
              switchCount: this.modelSwich.switchModel.switchCount,
              switchNum: this.modelSwich.switchModel.startNum,
              deviceNum: this.modelSwich.switchModel.deviceNum,
              manufacturerId: this.modelSwich.switchModel.factoryID,
              name: this.modelSwich.switchModel.name,
              remark: this.modelSwich.switchModel.remark,
              status: this.modelSwich.switchModel.status,
              gatewayId: this.modelSwich.switchModel.getwatID
,            }
          }
          request(obj).then(res => {
            if (res.code === '200') {
              uni.showToast({
                title: '新增成功',
                mask: true
              })
              this.showAddGroup = false
              this.getDeviceList()
            } else {
              uni.showToast({
                title: res.message,
                mask: true
              })
            }
            
          })
        }).catch(errors => {
          uni.$u.toast('校验失败')
        })
      },
      deviceTypeSelect(e){
        this.modelSwich.switchModel.gateway = e.name
        this.modelSwich.switchModel.myGetwayId = e.id
        
        if (this.tagFactory === 1 && this.modelSwich.switchModel.myGetwayId === 2) {
          const switchObj = {
            url: '/device/gatewayList',
            method: 'GET',
            data: {
              fId: this.modelSwich.switchModel.factoryID
            }
          }
          request(switchObj).then(result => {
            if (result.code === '200') {
              this.getwatArr = result.data
              this.isShowGetway = true
            } else {
              uni.$u.toast(result.message)
            }
          })
        } else {
          this.isShowGetway = false
        }
      },
      factorySelect(e){
        this.modelSwich.switchModel.factoryID = e.id
        this.modelSwich.switchModel.factory = e.mName
        this.tagFactory = e.isGateway
        if (this.tagFactory === 1 && this.modelSwich.switchModel.myGetwayId === 2) {
          const switchObj = {
            url: '/device/gatewayList',
            method: 'GET',
            data: {
              fId: e.id
            }
          }
          request(switchObj).then(result => {
            if (result.code === '200') {
              this.getwatArr = result.data
              this.isShowGetway = true
            } else {
              uni.$u.toast(result.message)
            }
          })
        } else {
          this.isShowGetway = false
        }
      },
      showGatewayFun(){
        this.sheetShowGateway = true
      },
      getwaySelect(e){
        this.modelSwich.switchModel.getwatID = e.id
        this.modelSwich.switchModel.getwatName = e.name
        this.sheetShowGateway = false
      },
		}
	}
</script>

<style lang="scss" scoped>
.selectDevice {
  z-index: 99;
  position: fixed;
  bottom: 100rpx;
  height: auto;
  text-align: center;
  padding: 20rpx 0;
  right: 50%;
  color: #fff;
  width: 200rpx;
  transform: translate(105rpx);
  background-image: linear-gradient(to right, #a4a5ee 40%, #cfcfe8);
}
.myFacility {
  width: 100%;
  height: 100rpx;
  background-image: linear-gradient(to right, #7979ed 40%, #a4a5ee);
  line-height: 100rpx;
  display: flex;
  justify-content: center;
  color: #fff;
}
.myFacility .realBox {
  height: 100%;
  min-width: 80%;
  width: auto;
  display: flex;
  justify-content: space-between
}
.setIcon {
  display: flex;
}
/deep/ .u-popup__content {
  border-radius: 10rpx;
}
.addBox {
  width: 80vw;
  height: auto;
  padding: 10rpx 20rpx;
  border-radius: 10rpx;
  .addTitle {
    width: 100%;
    font-size: 34rpx;
    font-weight: 600;
  }
}

.lastForSwitch {
  margin-top: 30rpx;
  width: 100%;
  display: flex;
  justify-content: space-around;
  :nth-child(1) {
    width: 30%;
    height: 80rpx;
    line-height: 80rpx;
    text-align: center;
    border-radius: 10rpx;
    background-color: #3c9cff;
    color: #fff;
  }
  :nth-child(2) {
    width: calc(30% - 2rpx);
    height: calc(80rpx - 2rpx);
    line-height: 78rpx;
    text-align: center;
    border-radius: 10rpx;
    border: 1rpx solid #909399;
    color: #000;
  }
}
.changeNow {
  margin: 20rpx 3%;
  width: 94%;
  height: auto;
}
.MainBody {
  margin: 20rpx 3%;
  width: 94%;
  height: auto;
}

.realBox_one {
  width: 95%;
  height: auto;
  border: 1rpx solid #000;
  margin: 15rpx auto;
  .deviceBox {
    width: 94%;
    margin: 10rpx 3%;
    padding: 20rpx 0;
    height: 50rpx;
    line-height: 50rpx;
    display: flex;
  }
  .lastForDevice {
    margin: 30rpx 0;
    width: 100%;
    display: flex;
    justify-content: space-around;
    .customButton {
      width: 40%;
      height: 80rpx;
      line-height: 80rpx;
      text-align: center;
      border-radius: 10rpx;
      color: #fff;
    }
    :nth-child(1) {
      background-color: #3c9cff;
    }
    :nth-child(2) {
      background-color: #d4237a;
    }
  }
}
.changeBox {
  box-shadow: 5rpx 5rpx 20px;
  width: 95%;
  height: auto;
  border: 1rpx solid #000;
  margin: 20rpx auto;
  position: relative;
  .deviceBox {
    width: 94%;
    margin: 10rpx 3%;
    padding: 20rpx 0;
    height: 50rpx;
    line-height: 50rpx;
    display: flex;
  }
  .radioPos {
    position: absolute;
    top: 30rpx;
    right: 30rpx;
  }
  .lastForDevice {
    margin: 30rpx 0;
    width: 100%;
    display: flex;
    justify-content: space-around;
    .customButton {
      width: 40%;
      height: 80rpx;
      line-height: 80rpx;
      text-align: center;
      border-radius: 10rpx;
      color: #fff;
    }
    :nth-child(1) {
      background-color: #3c9cff;
    }
    :nth-child(2) {
      background-color: #d4237a;
    }
  }
}
</style>
